package random.fox.p2p;

import android.app.ActionBar;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;

import com.google.gson.Gson;

import de.greenrobot.event.EventBus;
import flow.ActivityFlowSupport;
import flow.Backstack;
import flow.Flow;
import flow.path.Path;
import flow.path.PathContainerView;
import random.fox.p2p.event.FinishActivityEvent;
import random.fox.p2p.event.GetPicEvent;
import random.fox.p2p.event.PickPicEvent;
import random.fox.p2p.event.ProgressEvent;
import random.fox.p2p.pathview.GsonParceler;
import random.fox.p2p.pathview.HandlesBack;
import random.fox.p2p.util.Util;

/**
 * 主activity,用在注册登录流程上
 */
public class MainActivity extends ActionBarActivity implements Flow.Dispatcher {
    private String TAG = getClass().getSimpleName();

    private ActivityFlowSupport flowSupport;
    private PathContainerView container;
    private HandlesBack containerAsBackTarget;

    private ProgressDialog progressDialog;

    private Uri fileUri;
    private Uri cropUri;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        GsonParceler parceler = new GsonParceler(new Gson());
        Backstack defaultBackstack = Backstack.single(new Paths.SplashPath());
        @SuppressWarnings("deprecation") ActivityFlowSupport.NonConfigurationInstance nonConfig =
                (ActivityFlowSupport.NonConfigurationInstance) getLastNonConfigurationInstance();

        flowSupport =
                ActivityFlowSupport.onCreate(nonConfig,getIntent(),savedInstanceState, parceler, defaultBackstack);

        setContentView(R.layout.activity_main);

        progressDialog = new ProgressDialog(this);
        progressDialog.setMessage("加载中...");

        container = (PathContainerView) findViewById(R.id.container);
        containerAsBackTarget = (HandlesBack) container;
        getSupportActionBar().hide();

        //注册Eventbus,用来关闭Activity(第一作用。。。)
        EventBus.getDefault().register(this);

    }

    public void onEvent(FinishActivityEvent event) {
        finish();
    }

    public void onEvent(ProgressEvent event){
        if (isFinishing())
            return;
        if (event.isShow() && progressDialog!= null)
            progressDialog.show();
        else
            progressDialog.dismiss();
    }

    public void onEvent(PickPicEvent event){
        if (event.getType() == Util.CAMERA){
            fileUri = Util.getOutputMediaFileUri();
            Util.getPicByCamera(this,fileUri);
        }else if (event.getType() == Util.GALLERY){
            fileUri = Util.getOutputMediaFileUri();
            Util.getPicByGallery(this);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == Util.CAMERA){
            if (resultCode == RESULT_OK) {
                cropUri = Util.getOutputMediaFileUri();
                Util.cropPic(this,1,1,64,64,fileUri,cropUri);
            }else {
                Log.d(TAG,"拍照,但没有获得图片");
            }
        }else if (requestCode == Util.GALLERY){
            if (resultCode == RESULT_OK){
                fileUri = data.getData();
                cropUri = Util.getOutputMediaFileUri();
                Util.cropPic(this,1,1,64,64,fileUri, cropUri);
            }else {
                Log.d(TAG,"取消了图片选择");
            }
        }else if (requestCode == Util.CROP){
            if (resultCode == RESULT_OK) {
                EventBus.getDefault().post(new GetPicEvent(Util.getFileFromUri(this,cropUri)));
            }else {
                Log.d(TAG,"没有进行图片剪切");
            }
        }
    }

    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        flowSupport.onNewIntent(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
        flowSupport.onResume(this);
    }

    @Override
    protected void onPause() {
        flowSupport.onPause();
        super.onPause();
    }

    @Override
    public Object getSystemService(String name) {
        Object service = null;
        if (flowSupport != null) {
            service = flowSupport.getSystemService(name);
        }
        return service != null ? service : super.getSystemService(name);
    }

    @Override
    public void onBackPressed() {
        if (containerAsBackTarget.onBackPressed()) return;
        if (flowSupport.onBackPressed()) return;
        super.onBackPressed();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override public void dispatch(Flow.Traversal traversal, final Flow.TraversalCallback callback) {
        Path path = traversal.destination.current();
        setTitle(path.getClass().getSimpleName());
        ActionBar actionBar = getActionBar();
        boolean canGoBack = traversal.destination.size() > 1;
//        actionBar.setDisplayHomeAsUpEnabled(canGoBack);
//        actionBar.setHomeButtonEnabled(canGoBack);
        container.dispatch(traversal, new Flow.TraversalCallback() {
            @Override public void onTraversalCompleted() {
                invalidateOptionsMenu();
                callback.onTraversalCompleted();
            }
        });
    }

    @Override
    protected void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }
}
